/**
 * Copyright 2008 Matthew DeLambo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.delambo.drool.pooling;

import com.delambo.drool.interfaces.AtomicLockingArray;
import java.util.concurrent.atomic.*;

/**
 * Atomic reference array that adds locking functionality to each index in the 
 * array. Locking is implemented through a parallel, boolean atomic reference
 * array.
 * @author delambo
 * @param E type of reference/node for array. 
 */
public final class AtomicLockingArray_Impl<E> 
        extends AtomicReferenceArray<E> 
        implements AtomicLockingArray<E> {
    final private AtomicReferenceArray<Boolean> locks;
    final private boolean LOCKED = true;
    final private boolean UNLOCKED = false;
    final private int size;
    
    public AtomicLockingArray_Impl(int size) {
        super(size);
        this.size = size;
        this.locks = new AtomicReferenceArray<Boolean>(size);
    }
    
    /**
     * Tries to atomically lock the given index in this array by using a compare
     * and set on the parallel boolean array.
     * @param index allocation of pool to lock.
     * @return true if lock succeeds; otherwise, false.
     */
    public boolean tryLock(int index) {
        return this.locks.compareAndSet(index, UNLOCKED, LOCKED);
    }
    
    /**
     * Locks the given index in this array by setting the parallel boolean array.
     * @param index allocation of array.
     */
    public void lock(int index) {
        this.locks.set(index, LOCKED);
    }
    
    /**
     * Unlocks the specified index in this array by setting the parallel boolean 
     * array.
     * @param slot allocation in object pool to lock.
     */
    public void unlock(int index) {
        this.locks.set(index, UNLOCKED);
    }
    
    /**
     * Indicates whether or not a thread has a lock on the given index.
     * @param slot allocation in locked array.
     * @return true if slot is locked by another thread; otherwise, false.
     */
    public boolean locked(int index) {
        return this.locks.get(index);
    }
    
    /**
     * Returns the size of this array
     */
    public int getSize() {
        return this.size;
    }
    
    /**
     * Gets a node from the array.
     */
    public E getNode(int index) {
        return this.get(index);
    }
    
    /**
     * Sets a node into the array.
     */
    public void setNode(int index, E e) {
        this.set(index, e);
    }
}
